package com.marketlive.app.b2c.struts;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ActionConfigMatcher;
import org.apache.struts.config.ModuleConfig;

public class WildcardDelegatingTilesRequestProcessor extends PojoSpringTilesRequestsProcessor
{
  private static Log log = LogFactory.getLog(WildcardDelegatingTilesRequestProcessor.class);
  private HashMap actionConfigs;
  private NonReplacingActionConfigMatcher matcher;

  public WildcardDelegatingTilesRequestProcessor()
  {
    this.actionConfigs = null;

    this.matcher = null;
  }

  protected String determineActionBeanName(ActionMapping mapping)
  {
    ModuleConfig moduleConfig = mapping.getModuleConfig();

    String path = mapping.getPath();

    if ((this.actionConfigs == null) || (this.matcher == null)) {
      init(moduleConfig);
    }

    ActionConfig config = (ActionConfig)this.actionConfigs.get(path);

    if (config == null) {
      config = this.matcher.match(path);
    }

    String prefix = mapping.getModuleConfig().getPrefix();
    String matchedPath = config.getPath();
    String beanName = prefix + matchedPath;
    if (log.isDebugEnabled()) {
      log.debug("DelegatingActionProxy with mapping path '" + path + "' and module prefix '" + prefix + "' delegating to Spring bean with name [" + beanName + "]");
    }

    return beanName;
  }

  private void init(ModuleConfig moduleConfig)
  {
    synchronized (this) {
      if (this.actionConfigs == null) {
        this.actionConfigs = new HashMap();

        ActionConfig[] configs = moduleConfig.findActionConfigs();
        for (int i = 0; i < configs.length; i++) {
          this.actionConfigs.put(configs[i].getPath(), configs[i]);
        }

        this.matcher = new NonReplacingActionConfigMatcher(configs);
      }
    }
  }

  class NonReplacingActionConfigMatcher extends ActionConfigMatcher
  {
    private static final long serialVersionUID = -1421454331342275574L;

    public NonReplacingActionConfigMatcher(ActionConfig[] configs)
    {
      super(configs);
    }

    protected ActionConfig convertActionConfig(String path, ActionConfig orig, Map vars) {
      WildcardDelegatingTilesRequestProcessor.log.debug("returning the action:" + orig);
      return orig;
    }
  }
}